package controllers

import (
	"net/http"
	"xiaomi_demo/models"
	"xiaomi_demo/pkg/utils"

	"github.com/gin-gonic/gin"
)

type UserController struct{}
type ErrorInfo struct {
	Message string
	Errors  []string
	Data    string
}

// 用户注册
func (u UserController) Register(c *gin.Context) {
	// 接收用户名，密码，确认密码
	username := c.PostForm("username")
	password := c.PostForm("password")
	confirmPassword := c.PostForm("confirmPassword")
	errInfo := ErrorInfo{
		Message: "",
		Errors:  []string{},
	}
	if username == "" || password == "" || confirmPassword == "" {
		errInfo.Errors = append(errInfo.Errors, "请输入正确信息")
		c.HTML(401, "register.html", errInfo)
		return
	}
	if password != confirmPassword {
		errInfo.Errors = append(errInfo.Errors, "密码和确认密码不一致")
		c.HTML(402, "register.html", errInfo)
		return
	}
	user, _ := models.GetUserInfoByUsername(username)
	if user.Id != 0 {
		errInfo.Errors = append(errInfo.Errors, "用户名已存在")
		c.HTML(403, "register.html", errInfo)
		return
	}
	_, err := models.AddUser(username, EncryMd5(password))
	if err != nil {
		errInfo.Errors = append(errInfo.Errors, "保存失败，请联系管理员")
		c.HTML(404, "register.html", errInfo)
		return
	}
	c.Redirect(http.StatusFound, "/logins")
}

type UserApi struct {
	Id       int    `json:"id"`
	Username string `json:"username"`
}

// 登录
func (u UserController) Login(c *gin.Context) {
	// 接受用户名和密码
	username := c.PostForm("username")
	password := c.PostForm("password")
	errInfo := ErrorInfo{
		Message: "",
		Errors:  []string{},
	}
	if username == "" || password == "" {
		errInfo.Errors = append(errInfo.Errors, "请输入正确的信息")
		c.HTML(405, "login.html", errInfo)
		return
	}

	user, _ := models.GetUserInfoByUsername(username)
	if user.Id == 0 || user.Password != EncryMd5(password) {
		errInfo.Errors = append(errInfo.Errors, "用户名或密码不正确")
		c.HTML(406, "login.html", errInfo)
		return
	}

	// 密码验证成功后发一个token，为了其他功能需要身份验证所给前端存储的
	// 创建一个备忘录，这个功能就要token，不然不知道是谁创建的备忘录
	_, err := utils.GenerateToken(uint(user.Id), user.Username, user.Password)
	if err != nil {
		errInfo.Errors = append(errInfo.Errors, "签发Token失败")
		c.HTML(407, "login.html", errInfo)
		return
	}

	errInfo.Message = "登录成功"
	c.HTML(200, "login.html", errInfo)
}
